var product = {
    currentProductPageNo:0,
    
    currentRootCategoryId:0,
	
    createCategory:function(createMode){
    	var categoryLevel = $("input[name='categoryLevel']:checked").val();
    	var parentId = $('#rootCategories').val();
        var subject = $('#subject').val();
        var description = $('#description').val();
        var imagePath = $('#productCategoryFilePath').val();
    	if(!subject){
            $.msgBox.alert({
                title:'Tips',
                msg:'Subject is null,please input a value!',
                icon:'warning',
                width:350
            });
            return false;
    	}
        if(!description){
            $.msgBox.alert({
                title:'Tips',
                msg:'Description is null,please input a value!',
                icon:'warning',
                width:350
            });
            return false;
        }
        if(categoryLevel==0){
            if(!imagePath){
                $.msgBox.alert({
                    title:'Tips',
                    msg : 'Preview image is null,please select a image file!',
                    icon:'warning',
                    width:450
                });
                return false;
            }
        	parentId = 0;
        }else{
            if(!parentId){
                $.msgBox.alert({
                    title:'Tips',
                    msg : 'Please create a root category first!',
                    icon:'warning',
                    width:350
                });
                return false;
            }
        }
        
        $.ajax({
            type: "POST",
            url: "../products/categories/"+createMode+".json",
            cache:false,
            dataType: "json",
            data : {"id":$('#categoryId').val(),"subject":subject,"description":description,"imagePath":imagePath,"parentId":parentId},
            success: function(data){
                if(data.result == "success"){
                    $.msgBox.alert({
                        title:'Success',
                        msg:'Operate Success!',
                        icon:'warning',
                        width:250,
                        yesFun:function(){
                            $('#subject').val("");
                            $('#description').val("");
                            $('#productCategoryFilePath').val("");
                			$('#productCategoryImageForm').resetForm();
                			$('#productCategoryImage').attr('src','');
                        }
                    });
                }else{
                    $.msgBox.alert({
                        title:'Tips',
                        msg:'System error!Please try again later!',
                        icon:'warning',
                        width:350
                    });
                }
            }
       });
    },
    categoriesListByParentId:function(parentId,showType,referTo,selectedId){
    	$.ajax({
            type: "GET",
            url: "../products/categories/list.json",
            cache:false,
            dataType: "json",
            data : {"parentId":parentId},
            success: function(data){
                if(data.result == 'success'){
                	if(showType == 0){
                		product.constructRootCategories(data.categoriesList,referTo,selectedId);
                	}else{
                	    product.constructCategoriesList(data.categoriesList,referTo);
                	}
                }else{
                    $.msgBox.alert({
                        title:'Tips',
                        msg:'System error!Please try again later!',
                        icon:'warning',
                        width:350
                    });
                }
            }
        });
    },
    constructRootCategories:function(categoriesList,referTo,parentId){
        global.rootCategoriesMap = new HashMap();

		$('#'+referTo).empty();
		
    	$.each(categoriesList, function(index, obj) {
    		global.rootCategoriesMap.put(obj.id,obj.subject);
    		
    		var selectedFlag = obj.id == parentId?' selected="selected"':'';
    		
			var html = "<option value='"+obj.id+"'"+selectedFlag+">"+obj.subject+"</option>";

			$('#'+referTo).append(html);
		});
    },
    constructCategoriesList:function(categoriesList,referTo){
    	global.categoriesMap = new HashMap();
    	
    	$('#'+referTo).html("");
    	
        $.each(categoriesList, function(index, obj) {
        	global.categoriesMap.put(obj.id,obj);
        	
        	var parentCategoryName = global.rootCategoriesMap.get(obj.parentId);
        	
            var html = "<tr><td>"+obj.subject+"</td><td>"+obj.description+"</td>"+
            	"<td>"+(parentCategoryName?parentCategoryName:"Self")+"</td>"+
                "<td>"+new Date(obj.createDate).pattern("yyyy-MM-dd HH:mm:ss")+"</td>"+
                "<td><a href='javascript:product.topCategory("+obj.id+");'>Top</a> | " +
                "<a href='javascript:product.toModifyProductCategoryPage("+obj.id+","+obj.parentId+");'>Modify</a> | " +
                "<a href='javascript:product.deleteCategories("+obj.id+","+obj.parentId+");'>Delete</a></td></tr>";
                
            $('#'+referTo).append(html);
        });
    },
    topCategory:function(categoryId){
        $.ajax({
            type: "POST",
            url: "../products/categories/top.json",
            cache:false,
            dataType: "json",
            data : {"id":categoryId},
            success: function(data){
                if(data.result == "success"){
                    var categoryLevel = $("input[name='productCategoryLevel']:checked").val();
                    if(categoryLevel == 0){
                        product.categoriesListByParentId(0,1,'categoriesList');
                    }else{
                        product.categoriesListByParentId(product.currentRootCategoryId,1,'categoriesList');
                    }
                }else{
                    $.msgBox.alert({
                        title:'Tips',
                        msg:'System error!Please try again later!',
                        icon:'warning',
                        width:350
                    });
                }
            }
       });
    },
    deleteCategories:function(id,parentId){
        $.msgBox.prompt({
            title:'Tips',
            msg:'Are you sure delete this record?',
            icon:'warning',
            width:350,
            yesFun:function(){
                $.ajax({
                    type: "POST",
                    url: "../products/categories/delete.json",
                    cache:false,
                    dataType: "json",
                    data : {"id":id,"parentId":parentId},
                    success: function(data){
                        if(data.result == "success"){
                        	var categoryLevel = $("input[name='productCategoryLevel']:checked").val();
                        	if(categoryLevel == 0){
                                product.categoriesListByParentId(0,1,'categoriesList');
                        	}else{
                    			product.categoriesListByParentId(product.currentRootCategoryId,1,'categoriesList');
                        	}
                        }else{
                            $.msgBox.alert({
                                title:'Tips',
                                msg:'System error!Please try again later!',
                                icon:'warning',
                                width:350
                            });
                        }
                    }
               });
            }
        });
    },
    modifyProductCategory:function(categoryId){
        var obj = global.categoriesMap.get(categoryId);
        $('#categoryId').val(categoryId);
        $('#subject').val(obj.subject);
        $('#description').val(obj.description);
        $('#productCategoryFilePath').val(obj.imagePath);
        $('#productCategoryImage').attr("src",config.baseURL+obj.imagePath);
        
        $('#createProductCategoryButton').val('Modify');
    },
    create:function(createMode){
        var productNumber = $('#productNumber').val();
        var productName = $('#productName').val();
        var productSpec = $('#productSpec').val();
        var imagePath = $('#productFilePath').val();
        var productReadmeInfo = editor.getSource();
        if(!productNumber){
            $.msgBox.alert({
                title:'Tips',
                msg:'Number is null,please input a value!',
                icon:'warning',
                width:350
            });
            return false;
        }
        if(!productName){
            $.msgBox.alert({
                title:'Tips',
                msg:'Name is null,please input a value!',
                icon:'warning',
                width:350
            });
            return false;
        }
        if(!productSpec){
            $.msgBox.alert({
                title:'Tips',
                msg:'Spec is null,please input a value!',
                icon:'warning',
                width:350
            });
            return false;
        }
        if(!imagePath){
            $.msgBox.alert({
                title:'Tips',
                msg : 'Preview image is null,please select a image file!',
                icon:'warning',
                width:450
            });
            return false;
        }
        if(!productReadmeInfo){
            $.msgBox.alert({
                title:'Tips',
                msg:'Product readme is null,please input a value!',
                icon:'warning',
                width:400
            });
            return false;
        }
        $.ajax({
            type: "POST",
            url: "../products/"+createMode+".json",
            cache:false,
            dataType: "json",
            data : {
            	        "id":$('#productId').val(),
            			"newRelease": $('#newReleaseProduct').attr("checked")==undefined?0:1,
                        "number" : productNumber,
                        "name" : productName,
                        "spec" : productSpec,
                        "imagePath" : imagePath,
                        "productReadmeInfo" : productReadmeInfo,
                        "productCategories.id" : $('#categoriesList').val()
                    },
            success: function(data){
                if(data.result == 'success'){
                    $.msgBox.alert({
                        title:'Success',
                        msg:'Operate Success!',
                        icon:'warning',
                        width:250,
                        yesFun:function(){
                        	$('#productsListMenu').click();
                        }
                    });
                }else{
                    $.msgBox.alert({
                        title:'Tips',
                        msg:'System error!Please try again later!',
                        icon:'warning',
                        width:350
                    });
                }
            }
        });
    },
    modify:function(productId){
        $.ajax({
            type: "GET",
            url: "../products/detail.json",
            cache:false,
            dataType: "json",
            data : {"id":productId},
            success: function(data){
                if(data.result == 'success'){
                    var obj = data.product;
                    $('#productId').val(obj.id);
                    if(obj.newRelease == 1){
                        $('#newReleaseProduct').attr("checked","checked");
                    }
                    $('#categoriesList').val(obj.productCategories.id);
                    $('#productNumber').val(obj.number);
                    $('#productName').val(obj.name);
                    $('#productSpec').val(obj.spec);
                    $('#productFilePath').val(obj.imagePath);
                    $('#productImage').attr("src",config.baseURL+obj.imagePath);
                    editor.setSource(obj.productReadmeInfo);
                    
                    $('#publishProductButton').val("Modify");
                }else{
                    $.msgBox.alert({
                        title:'Tips',
                        msg:'System error!Please try again later!',
                        icon:'warning',
                        width:350
                    });
                }
            }
        });
    },
    topProduct:function(productId){
        $.ajax({
            type: "POST",
            url: "../products/top.json",
            cache:false,
            dataType: "json",
            data : {"id":productId},
            success: function(data){
                if(data.result == "success"){
                    product.list(currentProductPageNo);
                }else{
                    $.msgBox.alert({
                        title:'Tips',
                        msg:'System error!Please try again later!',
                        icon:'warning',
                        width:350
                    });
                }
            }
       });
    },
    list:function(page){
        $.ajax({
            type: "GET",
            url: "../products/list.json",
            cache:false,
            dataType: "json",
            data : {"currentPage":page + 1,"perPageSize":10},
            success: function(data){
                if(data.result == 'success'){
                    $('#productList').html("");

                    $.each(data.productList, function(index, obj) {
                    	var id = obj.id;
                    	var newReleaseChecked = null;
                    	if(obj.newRelease == 1){
                    		newReleaseChecked = "checked='true'";
                    	}
                        var html = "<tr><td>"+obj.number+"</td><td>"+obj.name+"</td><td>"+obj.spec+"</td>"+
                            "<td>"+obj.productCategories.subject+"</td><td>"+new Date(obj.createDate).pattern("yyyy-MM-dd HH:mm:ss")+"</td>"+
                            "<td><input type='checkbox' "+newReleaseChecked+" id='newRelease"+id+"' onclick='javascript:product.setNewRelease("+id+");'/></td>"+
                            "<td><a href='javascript:product.topProduct("+id+");'>Top</a> | " +
                            "<a href='javascript:product.toModifyProductPage("+id+");'>Modify</a> | "+
                            "<a href='javascript:product.deleteProduct("+id+");'>Delete</a></td></tr>";
                            
                        $('#productList').append(html);
                    });

                    $("#paginationDiv").pagination(data.productListCount, {
                        callback: product.list,//回调函数
                        num_display_entries: 5,
                        num_edge_entries: 3,
                        items_per_page:10,//每页显示多少条
                        current_page:page//当前页码
                    });
                    
                    currentProductPageNo = page;
                }else{
                    $.msgBox.alert({
                        title:'Tips',
                        msg:'System error!Please try again later!',
                        icon:'warning',
                        width:350
                    });
                }
            }
        });
    },
    deleteProduct:function(id){
        $.msgBox.prompt({
            title:'Tips',
            msg:'Are you sure delete this record?',
            icon:'warning',
            width:350,
            yesFun:function(){
                $.ajax({
                    type: "POST",
                    url: "../products/delete.json",
                    cache:false,
                    dataType: "json",
                    data : {"id":id},
                    success: function(data){
                        if(data.result == "success"){
                            product.list(currentProductPageNo);
                        }else{
                            $.msgBox.alert({
                                title:'Tips',
                                msg:'System error!Please try again later!',
                                icon:'warning',
                                width:350
                            });
                        }
                    }
               });
            }
        });
    },
    setNewRelease:function(id){
    	$.ajax({
            type: "POST",
            url: "../products/setNewRelease.json",
            cache:false,
            dataType: "json",
            data : {"id":id,"newRelease":$("#newRelease"+id).attr("checked")==undefined?0:1},
            success: function(data){
                if(data.result != "success"){
                    $.msgBox.alert({
                        title:'Tips',
                        msg:'System error!Please try again later!',
                        icon:'warning',
                        width:350
                    });
                }
            }
       });
    },
    toModifyProductPage:function(productId){
    	$('#loadCnt').load("product/productsList.jsp?productId="+productId);
    },
    toModifyProductCategoryPage:function(categoryId,parentId){
        $('#loadCnt').load("product/productCategories.jsp?categoryId="+categoryId+"&parentId="+parentId);
    }
};